package com.cjjd.c.feature.home.chekin.pay;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.cjjd.c.App;
import com.cjjd.c.EventBusKeys;
import com.cjjd.c.R;
import com.cjjd.c.ShareKeys;
import com.cjjd.c.base.ActionBarActivity;
import com.cjjd.c.bean.AliOrderBean;
import com.cjjd.c.bean.HttpResult;
import com.cjjd.c.bean.OrderBean;
import com.cjjd.c.bean.ToTipPayBean;
import com.cjjd.c.bean.WxPrepayBean;
import com.cjjd.c.bean.subscribe.GenBookOrderModel;
import com.cjjd.c.bean.subscribe.SaveOrderChangeBean;
import com.cjjd.c.feature.dialog.TextDialog;
import com.cjjd.c.feature.home.chekin.checklist_detail.CheckinDetailActivity;
import com.cjjd.c.feature.home.scan.ScanPaySuccessActivity;
import com.cjjd.c.http.CallbackImpl;
import com.cjjd.c.http.JsonUtils;
import com.cjjd.c.utils.ImageUtil;
import com.cjjd.c.utils.LogUtil;
import com.cjjd.c.utils.SharePrefUtil;
import com.cjjd.c.utils.ToastUtil;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.utils.Log;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Response;

/**
 * Created by Administrator on 2017/9/24.
 */

public class PayPledgeActivity extends ActionBarActivity {


    @Bind(R.id.iv_hotel_logo)
    ImageView ivHotelLogo;
    @Bind(R.id.tv_price)
    TextView tvPrice;
    @Bind(R.id.tv_yushouquan)
    TextView tvYushouquan;
    @Bind(R.id.tv_grade)
    TextView tvGrade;

    @Bind(R.id.btn_checkbox_wx)
    CheckBox checkboxWx;
    @Bind(R.id.btn_checkbox_alipay)
    CheckBox checkboxAliPay;

    @Bind(R.id.btn_pay)
    Button btnPay;

    // 来自入住页面
    public static final int PayCheckIn = 0x00000001;
    // 来自退房页面
    public static final int PayCheckOut = 0x00000002;
    // 来自赞赏页面
    public static final int PayReward = 0x00000003;
    // 来自扫一扫
    public static final int PayScan = 0x00000004;
    // 来自扫一扫是怎么处理？
    public static final int PaySelect = 0x00000005;
    // 来自预订单页面
    public static final int PayPreOrder = 0x00000006;
    // 来自修改订单页面
    public static final int PayChangeOrder = 0x00000007;

    private int fromPage = 0;
    // 入住
    private OrderBean prepayBean;

    // 打赏
    private ToTipPayBean toTipPayBean;

    @Override
    public Object getTitleString() {
//        return "支付押金(预授权)";
        return "支付";
    }

    @Override
    public int getContentView() {
        return R.layout.activity_pay_pledge;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);

        getIntentData();

        initView();


        ImageUtil.displayRoundImage("drawable://" + R.drawable.icon_item_favorite, ivHotelLogo, 200);
    }

    private String scanPayNo;
    private String scanPayMoney;

    // 预订单的订单Bean
    private GenBookOrderModel genBookOrder;

    // 修改订单
    private SaveOrderChangeBean saveOrderChangeBean;

    private void getIntentData() {
        fromPage = getIntent().getIntExtra("fromPage", 0);

        // 入住
        LogUtil.e("xyd", "来自哪个页面 " + fromPage);
        prepayBean = (OrderBean) getIntent().getSerializableExtra("prepaybean");
        if (prepayBean != null) {
            tvYushouquan.setText("  (预付款)");
            tvPrice.setText("￥" + prepayBean.payMoney);
            tvGrade.setText("订单编号: " + prepayBean.orderNo);
        }

        // 打赏
        toTipPayBean = (ToTipPayBean) getIntent().getSerializableExtra("toTipPay");
        if (toTipPayBean != null) {
            tvYushouquan.setText("  (打赏)");
            tvPrice.setText("￥" + toTipPayBean.tipAmount);
            tvGrade.setText("打赏" + toTipPayBean.positionName + " " + toTipPayBean.tipAmount + "元");
        }

        // 扫一扫
        scanPayNo = getIntent().getStringExtra("payNo");
        scanPayMoney = getIntent().getStringExtra("scanPayMoney");
        if (!TextUtils.isEmpty(scanPayMoney) && !TextUtils.isEmpty(scanPayNo)) {
            tvYushouquan.setText("  (餐饮服务)");
            tvPrice.setText("￥" + scanPayMoney);
            tvGrade.setText("订单编号: " + scanPayNo);
        }


        // TODO: 2017/11/30 客户手动下订单支付

        // 预订单
        genBookOrder = (GenBookOrderModel) getIntent().getSerializableExtra("genBookOrder");
        if (genBookOrder!=null){
            tvYushouquan.setText(" (不含保险)");
            tvPrice.setText("￥" + genBookOrder.price);
            tvGrade.setText("订单编号: " + genBookOrder.orderId);
        }

        // 修改订单
        saveOrderChangeBean = (SaveOrderChangeBean) getIntent().getSerializableExtra("saveOrderChangeBean");
        if (saveOrderChangeBean!=null){
            tvYushouquan.setText(" (改房差价)");
            tvPrice.setText("￥" + saveOrderChangeBean.price);
            tvGrade.setText("订单编号: " + saveOrderChangeBean.orderId);
        }


    }

    private void initView() {


        checkboxWx.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    checkboxAliPay.setChecked(false);
                }
            }
        });

        checkboxAliPay.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    checkboxWx.setChecked(false);
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        ButterKnife.unbind(this);
    }

    @OnClick({R.id.iv_hotel_logo, R.id.tv_price, R.id.btn_pay})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_hotel_logo:
                break;
            case R.id.tv_price:
                break;
            case R.id.btn_pay:

                // 先让服务器下订单
                if (checkboxWx.isChecked()) {
                    if (fromPage == PayCheckIn) {
                        getOrderWeixinPayInfo();
                    } else if (fromPage == PayReward) {
                        getOpenSignTipOrderInfo();
                    } else if (fromPage == PayScan) {
                        wxQrCodePay();
                    }else if (fromPage == PayPreOrder){
                        getBookOrderWeiXinPayInfo();
                    }else if (fromPage == PayPreOrder){
                        getChangeBookOrderWeiXinPayInfo();
                    }
                } else if (checkboxAliPay.isChecked()) {
                    if (fromPage == PayCheckIn) {
                        getOrderAliPayInfo();
                    } else if (fromPage == PayReward) {
                        getTipOrderAliPay();
                    } else if (fromPage == PayScan) {
                        zfbQrCodePay();
                    } else if (fromPage == PayPreOrder) {
                        getBookOrderAliPayInfo();
                    }else if (fromPage == PayPreOrder) {
                        getChangeBookOrderAliPayInfo();
                    }
                }

                break;
        }
    }


    /**
     * 修改订单  微信下单
     */
    private void getChangeBookOrderWeiXinPayInfo() {

        HashMap<String, Object> h1 = new HashMap<>();
        h1.put("token", SharePrefUtil.getString(mContext, ShareKeys.Token, ""));
        h1.put("sessionId", SharePrefUtil.getString(mContext, ShareKeys.sessionId, ""));
        // 修改订单uuid
        h1.put("orderUuid", saveOrderChangeBean.orderUuid);

        Call<HttpResult<WxPrepayBean>> call = service.getChangeBookOrderWeiXinPayInfo(JsonUtils.convertParam("getChangeBookOrderWeiXinPayInfo", h1));
        call.enqueue(new CallbackImpl<WxPrepayBean>() {
            @Override
            public void responseSuccess(Call<HttpResult<WxPrepayBean>> call, Response<HttpResult<WxPrepayBean>> response) {

                WxPrepayBean wxPrepayBean = response.body().getData();

                // 预订单成功之后，客户端进行支付。
                if (wxPrepayBean != null) {
                    LogUtil.e("xyd", "调用微信支付的sdk");
                    LogUtil.e("xyd", "请求参数是： " + "appid =" + wxPrepayBean.appid + " ; partnerid = " + wxPrepayBean.mch_id + " ; prepayid = " + wxPrepayBean.prepay_id
                            + "; packagevalue = " + wxPrepayBean.packageName + "; nonceStr = " + wxPrepayBean.nonce_str + "; timeStamp = " + wxPrepayBean.timestamp
                            + "; sign = " + wxPrepayBean.sign);

                    if (TextUtils.isEmpty(wxPrepayBean.mch_id) || TextUtils.isEmpty(wxPrepayBean.prepay_id) || TextUtils.isEmpty(wxPrepayBean.nonce_str)
                            || TextUtils.isEmpty(wxPrepayBean.timestamp) || TextUtils.isEmpty(wxPrepayBean.sign)) {
                        ToastUtil.showToast("请求支付参数错误");
                        return;
                    }

                    PayReq request = new PayReq();
                    request.appId = App.APP_ID;
                    request.partnerId = wxPrepayBean.mch_id;
                    request.prepayId = wxPrepayBean.prepay_id;
                    request.packageValue = "Sign=WXPay";
                    request.nonceStr = wxPrepayBean.nonce_str;
                    request.timeStamp = wxPrepayBean.timestamp;
                    request.sign = wxPrepayBean.sign;
                    App.WX_API.sendReq(request);


                    LogUtil.e("xyd", "支付调用结束");
                }
            }
        });
    }

    /**
     * 修改订单  支付宝下单
     */
    private void getChangeBookOrderAliPayInfo() {
        HashMap<String, Object> h1 = new HashMap<>();
        h1.put("token", SharePrefUtil.getString(mContext, ShareKeys.Token, ""));
        h1.put("sessionId", SharePrefUtil.getString(mContext, ShareKeys.sessionId, ""));
        //   修改订单uuid
        h1.put("orderUuid", saveOrderChangeBean.orderUuid);
        Call<HttpResult<AliOrderBean>> getChangeBookOrderAliPayInfo = service.getChangeBookOrderAliPayInfo(JsonUtils.convertParam("getChangeBookOrderAliPayInfo", h1));
        getChangeBookOrderAliPayInfo.enqueue(new CallbackImpl<AliOrderBean>() {
            @Override
            public void responseSuccess(Call<HttpResult<AliOrderBean>> call, Response<HttpResult<AliOrderBean>> response) {

                final String orderInfo = response.body().getData().payInfo;   // 订单信息

                Runnable payRunnable = new Runnable() {

                    @Override
                    public void run() {
                        PayTask alipay = new PayTask(PayPledgeActivity.this);
                        Map<String, String> result = alipay.payV2(orderInfo, true);

                        Message msg = new Message();
                        msg.what = SDK_PAY_FLAG;
                        msg.obj = result;
                        mHandler.sendMessage(msg);
                    }
                };
                // 必须异步调用
                Thread payThread = new Thread(payRunnable);
                payThread.start();

            }
        });
    }

    /**
     * 预订单  微信下单
     */
    private void getBookOrderWeiXinPayInfo() {

        HashMap<String, Object> h1 = new HashMap<>();
        h1.put("token", SharePrefUtil.getString(mContext, ShareKeys.Token, ""));
        h1.put("sessionId", SharePrefUtil.getString(mContext, ShareKeys.sessionId, ""));
        // 预订单uuid
        h1.put("orderUuid", genBookOrder.orderUuid);

        Call<HttpResult<WxPrepayBean>> call = service.getBookOrderWeiXinPayInfo(JsonUtils.convertParam("getBookOrderWeiXinPayInfo", h1));
        call.enqueue(new CallbackImpl<WxPrepayBean>() {
            @Override
            public void responseSuccess(Call<HttpResult<WxPrepayBean>> call, Response<HttpResult<WxPrepayBean>> response) {

                WxPrepayBean wxPrepayBean = response.body().getData();

                // 预订单成功之后，客户端进行支付。
                if (wxPrepayBean != null) {
                    LogUtil.e("xyd", "调用微信支付的sdk");
                    LogUtil.e("xyd", "请求参数是： " + "appid =" + wxPrepayBean.appid + " ; partnerid = " + wxPrepayBean.mch_id + " ; prepayid = " + wxPrepayBean.prepay_id
                            + "; packagevalue = " + wxPrepayBean.packageName + "; nonceStr = " + wxPrepayBean.nonce_str + "; timeStamp = " + wxPrepayBean.timestamp
                            + "; sign = " + wxPrepayBean.sign);

                    if (TextUtils.isEmpty(wxPrepayBean.mch_id) || TextUtils.isEmpty(wxPrepayBean.prepay_id) || TextUtils.isEmpty(wxPrepayBean.nonce_str)
                            || TextUtils.isEmpty(wxPrepayBean.timestamp) || TextUtils.isEmpty(wxPrepayBean.sign)) {
                        ToastUtil.showToast("请求支付参数错误");
                        return;
                    }

                    PayReq request = new PayReq();
                    request.appId = App.APP_ID;
                    request.partnerId = wxPrepayBean.mch_id;
                    request.prepayId = wxPrepayBean.prepay_id;
                    request.packageValue = "Sign=WXPay";
                    request.nonceStr = wxPrepayBean.nonce_str;
                    request.timeStamp = wxPrepayBean.timestamp;
                    request.sign = wxPrepayBean.sign;
                    App.WX_API.sendReq(request);


                    LogUtil.e("xyd", "支付调用结束");
                }
            }
        });
    }

    /**
     * 预订单  支付宝下单
     */
    private void getBookOrderAliPayInfo() {
        HashMap<String, Object> h1 = new HashMap<>();
        h1.put("token", SharePrefUtil.getString(mContext, ShareKeys.Token, ""));
        h1.put("sessionId", SharePrefUtil.getString(mContext, ShareKeys.sessionId, ""));
        //   预订单uuid
        h1.put("orderUuid", genBookOrder.orderUuid);
        Call<HttpResult<AliOrderBean>> getBookOrderAliPayInfo = service.getBookOrderAliPayInfo(JsonUtils.convertParam("getBookOrderAliPayInfo", h1));
        getBookOrderAliPayInfo.enqueue(new CallbackImpl<AliOrderBean>() {
            @Override
            public void responseSuccess(Call<HttpResult<AliOrderBean>> call, Response<HttpResult<AliOrderBean>> response) {

                final String orderInfo = response.body().getData().payInfo;   // 订单信息

                Runnable payRunnable = new Runnable() {

                    @Override
                    public void run() {
                        PayTask alipay = new PayTask(PayPledgeActivity.this);
                        Map<String, String> result = alipay.payV2(orderInfo, true);

                        Message msg = new Message();
                        msg.what = SDK_PAY_FLAG;
                        msg.obj = result;
                        mHandler.sendMessage(msg);
                    }
                };
                // 必须异步调用
                Thread payThread = new Thread(payRunnable);
                payThread.start();

            }
        });
    }

    /**
     * 扫一扫 微信下单
     */
    private void wxQrCodePay() {

        HashMap<String, Object> h1 = new HashMap<>();
        h1.put("token", SharePrefUtil.getString(mContext, ShareKeys.Token, ""));
        h1.put("sessionId", SharePrefUtil.getString(mContext, ShareKeys.sessionId, ""));
        // 扫一扫 支付 单号
        h1.put("payNo", scanPayNo);                 // 支付订单号

        Call<HttpResult<WxPrepayBean>> call = service.wxQrCodePay(JsonUtils.convertParam("wxQrCodePay", h1));
        call.enqueue(new CallbackImpl<WxPrepayBean>() {
            @Override
            public void responseSuccess(Call<HttpResult<WxPrepayBean>> call, Response<HttpResult<WxPrepayBean>> response) {

                WxPrepayBean wxPrepayBean = response.body().getData();

                // 预订单成功之后，客户端进行支付。
                if (wxPrepayBean != null) {
                    LogUtil.e("xyd", "调用微信支付的sdk");
                    LogUtil.e("xyd", "请求参数是： " + "appid =" + wxPrepayBean.appid + " ; partnerid = " + wxPrepayBean.mch_id + " ; prepayid = " + wxPrepayBean.prepay_id
                            + "; packagevalue = " + wxPrepayBean.packageName + "; nonceStr = " + wxPrepayBean.nonce_str + "; timeStamp = " + wxPrepayBean.timestamp
                            + "; sign = " + wxPrepayBean.sign);

                    if (TextUtils.isEmpty(wxPrepayBean.mch_id) || TextUtils.isEmpty(wxPrepayBean.prepay_id) || TextUtils.isEmpty(wxPrepayBean.nonce_str)
                            || TextUtils.isEmpty(wxPrepayBean.timestamp) || TextUtils.isEmpty(wxPrepayBean.sign)) {
                        ToastUtil.showToast("请求支付参数错误");
                        return;
                    }

                    PayReq request = new PayReq();
                    request.appId = App.APP_ID;
                    request.partnerId = wxPrepayBean.mch_id;
                    request.prepayId = wxPrepayBean.prepay_id;
                    request.packageValue = "Sign=WXPay";
                    request.nonceStr = wxPrepayBean.nonce_str;
                    request.timeStamp = wxPrepayBean.timestamp;
                    request.sign = wxPrepayBean.sign;
                    App.WX_API.sendReq(request);


                    LogUtil.e("xyd", "支付调用结束");
                }
            }
        });
    }

    /**
     * 扫一扫 生成支付宝预订单
     */
    private void zfbQrCodePay() {

        HashMap<String, Object> h1 = new HashMap<>();
        h1.put("token", SharePrefUtil.getString(mContext, ShareKeys.Token, ""));
        h1.put("sessionId", SharePrefUtil.getString(mContext, ShareKeys.sessionId, ""));
        //   扫一扫 单号
        h1.put("payNo", scanPayNo);
        Call<HttpResult<AliOrderBean>> zfbQrCodePay = service.zfbQrCodePay(JsonUtils.convertParam("zfbQrCodePay", h1));
        zfbQrCodePay.enqueue(new CallbackImpl<AliOrderBean>() {
            @Override
            public void responseSuccess(Call<HttpResult<AliOrderBean>> call, Response<HttpResult<AliOrderBean>> response) {

                final String orderInfo = response.body().getData().payInfo;   // 订单信息

                Runnable payRunnable = new Runnable() {

                    @Override
                    public void run() {
                        PayTask alipay = new PayTask(PayPledgeActivity.this);
                        Map<String, String> result = alipay.payV2(orderInfo, true);

                        Message msg = new Message();
                        msg.what = SDK_PAY_FLAG;
                        msg.obj = result;
                        mHandler.sendMessage(msg);
                    }
                };
                // 必须异步调用
                Thread payThread = new Thread(payRunnable);
                payThread.start();

            }
        });

    }

    /**
     * 打赏生成支付宝预订单
     */
    private void getTipOrderAliPay() {

        HashMap<String, Object> h1 = new HashMap<>();
        h1.put("token", SharePrefUtil.getString(mContext, ShareKeys.Token, ""));
        h1.put("sessionId", SharePrefUtil.getString(mContext, ShareKeys.sessionId, ""));
        //   打赏单号
        h1.put("payOrderId", toTipPayBean.payOrderId);
        Call<HttpResult<AliOrderBean>> getTipOrderAliPay = service.getTipOrderAliPay(JsonUtils.convertParam("getTipOrderAliPay", h1));
        getTipOrderAliPay.enqueue(new CallbackImpl<AliOrderBean>() {
            @Override
            public void responseSuccess(Call<HttpResult<AliOrderBean>> call, Response<HttpResult<AliOrderBean>> response) {

                final String orderInfo = response.body().getData().payInfo;   // 订单信息

                Runnable payRunnable = new Runnable() {

                    @Override
                    public void run() {
                        PayTask alipay = new PayTask(PayPledgeActivity.this);
                        Map<String, String> result = alipay.payV2(orderInfo, true);

                        Message msg = new Message();
                        msg.what = SDK_PAY_FLAG;
                        msg.obj = result;
                        mHandler.sendMessage(msg);
                    }
                };
                // 必须异步调用
                Thread payThread = new Thread(payRunnable);
                payThread.start();

            }
        });

    }

    /**
     * 打赏生成微信预订单
     */
    private void getOpenSignTipOrderInfo() {

        HashMap<String, Object> h1 = new HashMap<>();
        h1.put("token", SharePrefUtil.getString(mContext, ShareKeys.Token, ""));
        h1.put("sessionId", SharePrefUtil.getString(mContext, ShareKeys.sessionId, ""));
        // 微信打赏单号
        h1.put("payOrderId", toTipPayBean.payOrderId);                 // 支付订单号

        Call<HttpResult<WxPrepayBean>> call = service.getOpenSignTipOrderInfo(JsonUtils.convertParam("getOpenSignTipOrderInfo", h1));
        call.enqueue(new CallbackImpl<WxPrepayBean>() {
            @Override
            public void responseSuccess(Call<HttpResult<WxPrepayBean>> call, Response<HttpResult<WxPrepayBean>> response) {

                WxPrepayBean wxPrepayBean = response.body().getData();

                // 预订单成功之后，客户端进行支付。
                if (wxPrepayBean != null) {
                    LogUtil.e("xyd", "调用微信支付的sdk");
                    LogUtil.e("xyd", "请求参数是： " + "appid =" + wxPrepayBean.appid + " ; partnerid = " + wxPrepayBean.mch_id + " ; prepayid = " + wxPrepayBean.prepay_id
                            + "; packagevalue = " + wxPrepayBean.packageName + "; nonceStr = " + wxPrepayBean.nonce_str + "; timeStamp = " + wxPrepayBean.timestamp
                            + "; sign = " + wxPrepayBean.sign);

                    if (TextUtils.isEmpty(wxPrepayBean.mch_id) || TextUtils.isEmpty(wxPrepayBean.prepay_id) || TextUtils.isEmpty(wxPrepayBean.nonce_str)
                            || TextUtils.isEmpty(wxPrepayBean.timestamp) || TextUtils.isEmpty(wxPrepayBean.sign)) {
                        ToastUtil.showToast("请求支付参数错误");
                        return;
                    }

                    PayReq request = new PayReq();
                    request.appId = App.APP_ID;
                    request.partnerId = wxPrepayBean.mch_id;
                    request.prepayId = wxPrepayBean.prepay_id;
                    request.packageValue = "Sign=WXPay";
                    request.nonceStr = wxPrepayBean.nonce_str;
                    request.timeStamp = wxPrepayBean.timestamp;
                    request.sign = wxPrepayBean.sign;
                    App.WX_API.sendReq(request);


                    LogUtil.e("xyd", "支付调用结束");
                }
            }
        });

    }

    /**
     * 入住生成支付宝预订单
     */
    private void getOrderAliPayInfo() {

        HashMap<String, Object> h1 = new HashMap<>();
        h1.put("token", SharePrefUtil.getString(mContext, ShareKeys.Token, ""));
        h1.put("sessionId", SharePrefUtil.getString(mContext, ShareKeys.sessionId, ""));
        h1.put("payOrderId", prepayBean.payOrderId);
        Call<HttpResult<AliOrderBean>> getOrderAliPayInfo = service.getOrderAliPayInfo(JsonUtils.convertParam("getOrderAliPayInfo", h1));
        getOrderAliPayInfo.enqueue(new CallbackImpl<AliOrderBean>() {
            @Override
            public void responseSuccess(Call<HttpResult<AliOrderBean>> call, Response<HttpResult<AliOrderBean>> response) {

                final String orderInfo = response.body().getData().payInfo;   // 订单信息

                Runnable payRunnable = new Runnable() {

                    @Override
                    public void run() {
                        PayTask alipay = new PayTask(PayPledgeActivity.this);
                        Map<String, String> result = alipay.payV2(orderInfo, true);

                        Message msg = new Message();
                        msg.what = SDK_PAY_FLAG;
                        msg.obj = result;
                        mHandler.sendMessage(msg);
                    }
                };
                // 必须异步调用
                Thread payThread = new Thread(payRunnable);
                payThread.start();

            }
        });

    }


    /**
     * 调用接口，生成微信预订单  (入住)
     */
    private void getOrderWeixinPayInfo() {

        HashMap<String, Object> h1 = new HashMap<>();
        h1.put("token", SharePrefUtil.getString(mContext, ShareKeys.Token, ""));
        h1.put("sessionId", SharePrefUtil.getString(mContext, ShareKeys.sessionId, ""));
        h1.put("payOrderId", prepayBean.payOrderId);                 // 支付订单号

        Call<HttpResult<WxPrepayBean>> call = service.getOrderWeixinPayInfo(JsonUtils.convertParam("getOrderWeixinPayInfo", h1));
        call.enqueue(new CallbackImpl<WxPrepayBean>() {
            @Override
            public void responseSuccess(Call<HttpResult<WxPrepayBean>> call, Response<HttpResult<WxPrepayBean>> response) {

                WxPrepayBean wxPrepayBean = response.body().getData();

                // 预订单成功之后，客户端进行支付。
                if (wxPrepayBean != null) {
                    LogUtil.e("xyd", "调用微信支付的sdk");
                    LogUtil.e("xyd", "请求参数是： " + "appid =" + wxPrepayBean.appid + " ; partnerid = " + wxPrepayBean.mch_id + "prepayid = " + wxPrepayBean.prepay_id
                            + "; packagevalue = " + wxPrepayBean.packageName + "; nonceStr = " + wxPrepayBean.nonce_str + "; timeStamp = " + wxPrepayBean.timestamp
                            + "; sign = " + wxPrepayBean.sign);

                    if (TextUtils.isEmpty(wxPrepayBean.mch_id) || TextUtils.isEmpty(wxPrepayBean.prepay_id) || TextUtils.isEmpty(wxPrepayBean.nonce_str)
                            || TextUtils.isEmpty(wxPrepayBean.timestamp) || TextUtils.isEmpty(wxPrepayBean.sign)) {
                        ToastUtil.showToast("请求支付参数错误");
                        return;
                    }

                    PayReq request = new PayReq();
                    request.appId = App.APP_ID;
                    request.partnerId = wxPrepayBean.mch_id;
                    request.prepayId = wxPrepayBean.prepay_id;
                    request.packageValue = "Sign=WXPay";
                    request.nonceStr = wxPrepayBean.nonce_str;
                    request.timeStamp = wxPrepayBean.timestamp;
                    request.sign = wxPrepayBean.sign;
                    App.WX_API.sendReq(request);

                    LogUtil.e("xyd", "支付调用结束");
                }
            }
        });
    }


    // 支付宝的支付结果处理
    private static final int SDK_PAY_FLAG = 1;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        if (fromPage == PayCheckIn) {
                            Intent intent = new Intent(PayPledgeActivity.this, PaySuccessedActivity.class);
                            startActivity(intent);
                        } else if (fromPage == PayReward) {
                            new TextDialog(mContext, "感谢您的打赏", "您的支持是对我们最大的鼓励", new TextDialog.OnCloseListener() {
                                @Override
                                public void OnClick() {
                                    EventBus.getDefault().post(EventBusKeys.hadPayReward);
                                    finish();
                                }
                            }).show();
                        } else if (fromPage == PayScan) {
                            Intent scanPaySucessIntent = new Intent(mContext, ScanPaySuccessActivity.class);
                            startActivity(scanPaySucessIntent);
                        } else if (fromPage == PayPreOrder) {
                            Intent intent = new Intent(mContext, CheckinDetailActivity.class);
                            intent.putExtra("mainUuid", genBookOrder.orderUuid);
                            mContext.startActivity(intent);
                            //  2017/12/20 预订单支付成功以后，需要关闭预订单的相关页面
                            EventBus.getDefault().post(EventBusKeys.finishPreOrder);
                        }else if (fromPage ==PayChangeOrder) {
                            Intent intent = new Intent(mContext, CheckinDetailActivity.class);
                            intent.putExtra("mainUuid", saveOrderChangeBean.orderUuid);
                            mContext.startActivity(intent);
                            // TODO: 2017/12/20 修改订单支付成功以后，需要关闭修改订单的相关页面
                        }
                        //Toast.makeText(PayPledgeActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(PayPledgeActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }
                default:
                    break;
            }
        }

        ;
    };


    // 微信的支付结果处理
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(String event) {
        if (EventBusKeys.hadPay.equals(event)) {
            // goto pay success page
            if (fromPage == PayCheckIn) {
                Intent intent = new Intent(this, PaySuccessedActivity.class);
                startActivity(intent);
            } else if (fromPage == PayReward) {

                new TextDialog(mContext, "感谢您的打赏", "您的支持是对我们最大的鼓励", new TextDialog.OnCloseListener() {
                    @Override
                    public void OnClick() {
                        EventBus.getDefault().post(EventBusKeys.hadPayReward);
                        finish();
                    }
                }).show();

            } else if (fromPage == PayScan) {
                Intent scanPaySucessIntent = new Intent(mContext, ScanPaySuccessActivity.class);
                startActivity(scanPaySucessIntent);
            }else if (fromPage == PayPreOrder) {
                Intent intent = new Intent(mContext, CheckinDetailActivity.class);
                intent.putExtra("mainUuid", genBookOrder.orderUuid);
                mContext.startActivity(intent);
                // 2017/12/20 预订单支付成功以后，需要关闭预订单的相关页面
                EventBus.getDefault().post(EventBusKeys.finishPreOrder);

            }else if (fromPage ==PayChangeOrder) {
                Intent intent = new Intent(mContext, CheckinDetailActivity.class);
                intent.putExtra("mainUuid", saveOrderChangeBean.orderUuid);
                mContext.startActivity(intent);
                // TODO: 2017/12/20 修改订单支付成功以后，需要关闭修改订单的相关页面
            }
        }

        if (EventBusKeys.hadPayCheckIn.equals(event)
                || EventBusKeys.hadPayScan.equals(event)
                || EventBusKeys.finishPreOrder.equals(event)) {
            Log.e("xyd", "接收到的信息是" + event);
            finish();
        }

    }

}
